package net.starwifi.duobao.web;


import net.starwifi.duobao.entity.Article;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.mvc.Order;
import net.starwifi.duobao.mvc.PageView;
import net.starwifi.duobao.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller("adminArticleController")
@RequestMapping("/article")
public class ArticleController extends BaseController {

    @Autowired
    private ArticleService articleService;

    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model) {
        return "/article/add";
    }

    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Article entity, RedirectAttributes redirectAttributes) {
        if (!isValid(entity)) {
            return ERROR_VIEW;
        }
        articleService.save(entity);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.do";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model) {
        model.addAttribute("entity", articleService.find(id));
        return "/article/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Article entity, RedirectAttributes redirectAttributes) {
        if (!isValid(entity)) {
            return ERROR_VIEW;
        }
        articleService.update(entity, "hits");
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.do";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(PageView pageView, ModelMap model,HttpServletRequest request) {
        pageView.filterQuery(request);
        pageView.addOrder(Order.desc("id"));
        model.addAttribute("page", articleService.getScrollData(pageView));
        return "/article/list";
    }

    /**
     * 删除
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Message delete(Long[] ids) {
        articleService.delete(ids);
        return SUCCESS_MESSAGE;
    }

}
